<template>
  <div class="dashboard-wrapper">
    <!-- 数据概览卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-shopping-cart-full stat-icon"></i>
          <div class="stat-title">本月订单</div>
        </div>
        <div class="stat-value">
          <count-to :start-val="0" :end-val="orderStats.currentMonthOrders" :duration="2000">
          </count-to>
        </div>
        <div class="stat-footer">
          较上月
          <span :class="orderTrend >= 0 ? 'up' : 'down'">
            {{ orderStats.growthRate }}
            <i :class="orderTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          </span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-money stat-icon"></i>
          <div class="stat-title">本月销售额</div>
        </div>
        <div class="stat-value">
          ¥<count-to :start-val="0" :end-val="salesStats.currentMonthSales" :duration="2000" :decimals="2">
          </count-to>
        </div>
        <div class="stat-footer">
          较上月
          <span :class="saleTrend >= 0 ? 'up' : 'down'">
            {{ salesStats.growthRate }}
            <i :class="saleTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          </span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-header">
          <i class="el-icon-user stat-icon"></i>
          <div class="stat-title">今年用户数</div>
        </div>
        <div class="stat-value">
          <count-to :start-val="0" :end-val="userStats.currentYearUsers" :duration="2000">
          </count-to>
        </div>
        <div class="stat-footer">
          较去年
          <span :class="userTrend >= 0 ? 'up' : 'down'">
            {{ userStats.growthRate }}
            <i :class="userTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
          </span>
        </div>
      </el-card>
    </div>

    <div class="content-wrapper">
      <!-- 热销商品TOP5图表 -->
      <el-card class="chart-card" shadow="hover">
        <div class="chart-header">
          <span>热销商品 TOP5</span>
          <el-button type="primary" link @click="fetchTopProducts">刷新</el-button>
        </div>
        <div class="chart-content">
          <div ref="topProductsChartRef" class="chart"></div>
        </div>
      </el-card>

      <!-- 品类销售占比图表 -->
      <el-card class="chart-card" shadow="hover">
        <div class="chart-header">
          <span>品类销售占比</span>
          <el-button type="primary" link @click="fetchCategoryStats">刷新</el-button>
        </div>
        <div class="chart-content">
          <div ref="categoryChartRef" class="chart"></div>
        </div>
      </el-card>
    </div>

    <!-- 通知公告 -->
    <div class="content-wrapper">
      <el-card class="notice-card" shadow="hover">
        <div class="notice-header">
          <span>通知公告</span>
          <el-button type="primary" link @click="fetchData">刷新</el-button>
        </div>
        <div class="notice-content">
          <el-timeline>
            <el-timeline-item v-for="(notice, index) in announcements" :key="index" :timestamp="notice.time" :type="getNoticeType(notice.type)">
              <el-card class="notice-item" shadow="never">
                <h4>{{ notice.title }}</h4>
                <p class="notice-text">{{ notice.content }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import CountTo from '@/components/vue-countTo.vue'
import Request from '../utils/request.js'
import * as echarts from 'echarts'
import { ElCard, ElTimeline, ElTimelineItem, ElButton } from 'element-plus'

// 定义响应式数据
const noticeLimit = ref(10)
const announcements = ref([])

// 统计数据
const orderStats = reactive({
  currentMonthOrders: 0,
  lastMonthOrders: 0,
  growthRate: '0.00%'
})

const salesStats = reactive({
  currentMonthSales: 0,
  lastMonthSales: 0,
  growthRate: '0.00%'
})

const userStats = reactive({
  currentYearUsers: 0,
  lastYearUsers: 0,
  growthRate: '0.00%'
})

// 图表引用
const topProductsChartRef = ref(null)
const categoryChartRef = ref(null)
const topProductsChart = ref(null)
const categoryChart = ref(null)

// 热销商品和品类数据
const topProducts = ref([])
const categoryStats = ref([])

// 计算属性
const orderTrend = computed(() => {
  return orderStats.currentMonthOrders - orderStats.lastMonthOrders
})

const saleTrend = computed(() => {
  return salesStats.currentMonthSales - salesStats.lastMonthSales
})

const userTrend = computed(() => {
  return userStats.currentYearUsers - userStats.lastYearUsers
})

// 获取通知公告数据
const fetchData = async () => {
  try {
    const response = await Request.get('/notice/page', {
      params: {
        currentPage: 1,
        size: noticeLimit.value
      }
    })
    if (response.code === '0') {
      announcements.value = response.data.records
    }
  } catch (error) {
    console.error('获取通知公告失败:', error)
  }
}

// 获取订单统计数据
const fetchOrderStats = async () => {
  try {
    const response = await Request.get('/statistics/orders/monthly')
    if (response.code === '0' && response.data.orderStats) {
      const stats = response.data.orderStats
      orderStats.currentMonthOrders = stats.currentMonthOrders
      orderStats.lastMonthOrders = stats.lastMonthOrders
      orderStats.growthRate = stats.growthRate
    }
  } catch (error) {
    console.error('获取订单统计数据失败:', error)
  }
}

// 获取销售统计数据
const fetchSalesStats = async () => {
  try {
    const response = await Request.get('/statistics/sales/monthly')
    if (response.code === '0' && response.data.salesStats) {
      const stats = response.data.salesStats
      salesStats.currentMonthSales = stats.currentMonthSales
      salesStats.lastMonthSales = stats.lastMonthSales
      salesStats.growthRate = stats.growthRate
    }
  } catch (error) {
    console.error('获取销售统计数据失败:', error)
  }
}

// 获取用户统计数据
const fetchUserStats = async () => {
  try {
    const response = await Request.get('/statistics/users/yearly')
    console.log('用户数据接口响应:', response); // 已确认返回正常
    // 关键修改：去掉 .userStats，直接用 response.data
    if (response.code === '0' && response.data) {
      const stats = response.data; // 此时 stats 就是 {currentYearUsers:10, ...}
      userStats.currentYearUsers = stats.currentYearUsers; // 直接赋值
      userStats.lastYearUsers = stats.lastYearUsers;
      userStats.growthRate = stats.growthRate;
      console.log('用户数据更新成功:', userStats); // 新增日志，确认赋值
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error);
  }
}

// 初始化热销商品图表
const initTopProductsChart = () => {
  if (topProductsChartRef.value) {
    topProductsChart.value = echarts.init(topProductsChartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: false,
      width: 'auto',
      height: 'auto'
    })
    updateTopProductsChart()
  }
}

// 更新热销商品图表数据
const updateTopProductsChart = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: topProducts.value.map(item => item.name),
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '销量',
        type: 'bar',
        barWidth: '60%',
        data: topProducts.value.map(item => item.salesCount),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  if (topProductsChart.value) {
    topProductsChart.value.setOption(option)
  }
}

// 获取热销商品数据
const fetchTopProducts = async () => {
  try {
    const response = await Request.get('/statistics/products/top5')
    if (response.code === '0' && response.data.topProducts) {
      topProducts.value = response.data.topProducts
      nextTick(() => {
        updateTopProductsChart()
      })
    }
  } catch (error) {
    console.error('获取热销商品数据失败:', error)
  }
}

// 初始化品类图表
const initCategoryChart = () => {
  if (categoryChartRef.value) {
    categoryChart.value = echarts.init(categoryChartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: false,
      width: 'auto',
      height: 'auto'
    })
    updateCategoryChart()
  }
}

// 更新品类图表数据
const updateCategoryChart = () => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '品类销售',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: categoryStats.value.map(item => ({
          name: item.name,
          value: item.salesCount
        }))
      }
    ],
    color: [
      '#409EFF', '#67C23A', '#E6A23C', '#F56C6C',
      '#909399', '#36CBCB', '#FFA2D3', '#9A60B4'
    ]
  }
  if (categoryChart.value) {
    categoryChart.value.setOption(option)
  }
}

// 获取品类统计数据
const fetchCategoryStats = async () => {
  try {
    const response = await Request.get('/statistics/category/sales')
    if (response.code === '0' && response.data.categoryStats) {
      categoryStats.value = response.data.categoryStats
      nextTick(() => {
        updateCategoryChart()
      })
    }
  } catch (error) {
    console.error('获取品类统计数据失败:', error)
  }
}

// 获取通知类型
const getNoticeType = (type) => {
  const typeMap = {
    '重要': 'danger',
    '紧急': 'warning',
    '普通': 'info',
    '公告': 'success'
  }
  return typeMap[type] || 'info'
}

// 组件挂载时初始化
onMounted(() => {
  fetchData()
  fetchOrderStats()
  fetchSalesStats()
  fetchUserStats()
  fetchTopProducts()
  fetchCategoryStats()

  nextTick(() => {
    initTopProductsChart()
    initCategoryChart()
  })

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    if (topProductsChart.value) {
      topProductsChart.value.resize()
    }
    if (categoryChart.value) {
      categoryChart.value.resize()
    }
  })
})

// 组件销毁前清理
onBeforeUnmount(() => {
  if (topProductsChart.value) {
    topProductsChart.value.dispose()
  }
  if (categoryChart.value) {
    categoryChart.value.dispose()
  }
})
</script>

<style lang="less" scoped>
.dashboard-wrapper {
  padding: 20px;
}

.stat-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  min-width: 240px;

  .stat-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }

  .stat-icon {
    font-size: 24px;
    margin-right: 12px;
    color: #409eff;
  }

  .stat-title {
    font-size: 16px;
    color: #606266;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
  }

  .stat-footer {
    font-size: 14px;
    color: #909399;

    .up {
      color: #67c23a;
    }

    .down {
      color: #f56c6c;
    }
  }
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-top: 20px;

  .chart-card {
    flex: 1;
    min-width: 400px;
  }

  .notice-card {
    flex: 1;
    min-width: 400px;
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.chart-content {
  height: 400px;
  .chart {
    width: 100%;
    height: 100%;
  }
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.notice-content {
  max-height: 600px;
  overflow-y: auto;
}

.notice-item {
  margin-bottom: 8px;

  h4 {
    margin: 0 0 8px;
    color: #303133;
  }

  .notice-text {
    color: #606266;
    margin: 0;
    line-height: 1.6;
  }
}

:deep(.el-timeline-item__node--primary) {
  background-color: #409eff;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67c23a;
}

:deep(.el-timeline-item__node--warning) {
  background-color: #e6a23c;
}

:deep(.el-timeline-item__node--danger) {
  background-color: #f56c6c;
}

/* 确保图表容器有最小高度 */
.chart {
  min-height: 300px;
}

/* 适配小屏幕 */
@media screen and (max-width: 1200px) {
  .content-wrapper {
    flex-direction: column;

    .chart-card,
    .notice-card {
      width: 100%;
    }
  }
}
</style>